package at.guthy;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;

import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

import com.google.gdata.data.media.mediarss.MediaThumbnail;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.util.AuthenticationException;

public class PicasaAlbumSelector extends JComboBox implements ActionListener {
	private static PicasaAlbumSelector instance;
	
	public static PicasaAlbumSelector getInstance() {
		if(instance == null) {
			instance = new PicasaAlbumSelector();
		}
		return instance;
	}
	private PicasaAlbumSelector() {
		super();
		this.refresh();
		this.addActionListener(this);
		ComboBoxRenderer renderer = new ComboBoxRenderer();
		this.setRenderer(renderer);
		PicasaWindow.picturesTable.reload(((AlbumEntry) this.getItemAt(0)));
	}

	public void refresh() {
		this.removeAllItems();
		try {
			for (AlbumEntry ae : PicasaClient.getInstance().getAlbums()) {
				this.addItem(ae);
			}
		}
		catch (AuthenticationException e) {
			e.printStackTrace();
			PicasaWindow.progressBar.setString("H");
		}
	}

	public void actionPerformed(ActionEvent evt) {
		JComboBox cb = (JComboBox) evt.getSource();
		try {
			PicasaWindow.picturesTable.reload(((AlbumEntry) cb.getSelectedItem()));
		}
		catch (Exception e) {}
	}

	class ComboBoxRenderer extends JLabel implements ListCellRenderer {
		public ComboBoxRenderer() {
			setOpaque(true);
			setHorizontalAlignment(LEFT);
		}

		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
			if (value != null) {
				AlbumEntry album = (AlbumEntry) value;

				this.setText(album.getTitle().getPlainText());
				try {
					ImageIcon icon = new ImageIcon(new java.net.URL(album.getMediaThumbnails().get(0).getUrl()));
					this.setIcon(icon);
				}
				catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
			return this;
		}
	}
}